import { Router } from 'vue-router';
import { usePermissionStoreOutside } from '@/store/modules/permission';
import { useUserStoreOutside } from '@/store/modules/user';
import { RootRoute } from '../routes';
import { PageEnum } from '@/enums/pageEnum';
import { PAGE_NOT_FOUND_ROUTE } from '../routes/basic';

const LOGIN_PATH = PageEnum.BASE_LOGIN;
const ROOT_PATH = RootRoute.path;

const whitePathList: PageEnum[] = [PageEnum.BASE_LOGIN];

export function createPermissionGuard(router: Router) {
	const userStore = useUserStoreOutside();
	const permissionStore = usePermissionStoreOutside();
	router.beforeEach(async (to, from, next) => {
		// 修改登录后默认跳转
		if (from.path === ROOT_PATH && to.path === PageEnum.BASE_HOME && userStore.getHomePath !== PageEnum.BASE_HOME) {
			next(userStore.getHomePath);
			return;
		}

		const token = userStore.getToken;

		if (whitePathList.includes(to.path as PageEnum)) {
			if (to.path === LOGIN_PATH && token) {
				try {
					await userStore.afterLoginAction();
					next((to.query?.redirect as string) || '/');
					return;
				} catch {}
			}
			next();
			return;
		}

		if (!token) {
			if (to.meta.ignoreAuth) {
				next();
				return;
			}

			const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
				path: LOGIN_PATH,
				replace: true,
			};
			if (to.path) {
				redirectData.query = {
					...redirectData.query,
					redirect: to.path,
				};
			}
			next(redirectData);
			return;
		}

		if (
			from.path === LOGIN_PATH &&
			to.name === PAGE_NOT_FOUND_ROUTE.name &&
			to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
		) {
			next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
			return;
		}

		if (userStore.getLastUpdateTime === 0) {
			try {
				await userStore.getUserInfoAction();
			} catch (err) {
				next();
				return;
			}
		}

		if (permissionStore.getIsDynamicAddedRoute) {
			next();
			return;
		}

		const routes = await permissionStore.buildRoutesAction();

		permissionStore.generateRoutes(routes);

		if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
			// 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
			next({ path: to.fullPath, replace: true, query: to.query });
		} else {
			const redirectPath = (from.query.redirect || to.path) as string;
			const redirect = decodeURIComponent(redirectPath);
			const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
			next(nextData);
		}
	});
}
